#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

#include "user_io.h"
#include "user_threads.h"

int uthread_open(const char * filename, int flags)
{
	int ret = -1;

	if (NULL == filename) {
		goto out;
	}
	ret = open(filename, flags | O_NONBLOCK);
out:
	return ret;
}

int uthread_pipe(int filedes[2])
{
	int ret = -1, flags = 0, i = -1;

	if (NULL == filedes) {
		goto out;
	}
	ret = pipe(filedes);
	if (ret == 0) {
		for (i = 0; i < 2; i++) {
			flags = fcntl(filedes[i], F_GETFL);
			fcntl(filedes[i], F_SETFL, flags | O_NONBLOCK);
		}
	}
out:
	return ret;
}

int uthread_read(int fd, void * buf, size_t count)
{
	int ret = -1;

	if (NULL == buf) {
		goto out;
	}
	ret = read(fd, buf, count);
	while ((ret == -1) && (errno == EAGAIN)) {
		uthread_yield();
		ret = read(fd, buf, count);
	}
out:
	return ret;
}

int uthread_write(int fd, const void * buf, size_t count)
{
	int ret = -1;

	if (NULL == buf) {
		goto out;
	}
	ret = write(fd, buf, count);
	while ((ret == -1) && (errno == EAGAIN)) {
		uthread_yield();
		ret = write(fd, buf, count);
	}
out:
	return ret;
}
